package utils;

import java.sql.*;
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantLock;

public class JdbcUtils {
    private static String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://192.168.26.128:3306/zjc?useSSL=false&serverTimezone=UTC";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "Root@123456";
    private static Integer INITIAL_POOL_SIZE = 5;
    private static Integer MAX_POOL_SIZE = 10;
    private static final LinkedList<Connection> CONNECTIONS_POOLS = new LinkedList<>();
    private static final ReentrantLock LOCK = new ReentrantLock();

    static {
        try {
            Class.forName(DRIVER);
            // 初始化连接池
            for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
                Connection conn = createConnection();
                if (conn != null) {
                    CONNECTIONS_POOLS.add(conn);
                }
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化数据库连接池失败: " + e.getMessage());
        }
    }
    private static Connection createConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
    public static Connection getConnection() throws SQLException {
        LOCK.lock();
        try {
            if (CONNECTIONS_POOLS.isEmpty()) {
                if (CONNECTIONS_POOLS.size() < MAX_POOL_SIZE) {
                    CONNECTIONS_POOLS.add(createConnection());
                } else {
                    throw new SQLException("连接池已满！");
                }
            }
            return CONNECTIONS_POOLS.removeFirst();
        } finally {
            LOCK.unlock();
        }
    }
    public static void releaseConnection(Connection connection) {
        LOCK.lock();
        try {
            if (connection != null) {
                CONNECTIONS_POOLS.addLast(connection);
            }
        }finally {
            LOCK.unlock();
        }
    }
    public void closeAllConnections() {
        LOCK.lock();
        try {
            for (Connection connection : CONNECTIONS_POOLS) {
                if (connection != null && !connection.isClosed()) {
                    try {
                        connection.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            CONNECTIONS_POOLS.clear();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            LOCK.unlock();
        }
    }

    public static void closeResource(ResultSet rs, PreparedStatement ps){
        try {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

